package com.gorkr;



import java.util.LinkedList;
import java.util.Objects;
import java.util.TreeMap;

class TreeNode {
 int val;
 TreeNode left;
 TreeNode right;
 TreeNode(int x) { val = x; }
}



/**
 * 二叉树的序列化与反序列化
 *
 * Integer 不是引用类型吗？？？
 * 我需要维护一个 递归一次增加一的变量
 */

public class L297 {




    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        buildString(sb,root);
        System.out.println(sb);

        return sb.toString();
    }

    public void buildString(StringBuilder sb, TreeNode root){
        if(root==null){
            sb.append('#').append(',');
            return;
        }
        sb.append(Integer.toString(root.val)).append(',');
        buildString(sb,root.left);
        buildString(sb,root.right);
    }
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] split = data.split(",");
        TreeNode root = new TreeNode(-1);
        buildTree(split,root,0);
        return root;

    }

    public TreeNode buildTree(LinkedList<String> nodes){
        if(nodes.isEmpty()) return null;
        String first = nodes.removeFirst();
        if(first.equals("#"))return null;
        TreeNode root = new TreeNode(Integer.parseInt(first));
        root.left = buildTree(nodes);
        root.right = buildTree(nodes);

        return root;
    }



//     可以用LinkedList 处理递归中n增长的问题
//    使用全局变量
    public  void  buildTree(String[] split,  TreeNode root, int n){
        System.out.println(n);
        // base case
        if(Objects.equals(split[n], "#")){
            root=null;
            ++n;

            return;
        }

        root = new TreeNode(Integer.parseInt(split[n]));

        n++;
        buildTree(split,root.left, n);
        n++;
        buildTree(split,root.right, n);
    }




    public static void main(String[] args) {
        L297 l = new L297();

        String data = "1,2,#,#,3,4,#,#,5,#,#,";
        TreeNode root = new TreeNode(-1);
        String[] split = data.split(",");
        l.buildTree(split,root,0);

    }



}
